// controllers/fileController.js
const path = require('path');
const db = require('../db');

// 单个文件上传
async function uploadFile(ctx) {
  const file = ctx.req.file;
  const { originalname, mimetype, filename, size, path: filepath } = file;
  const relativePath = path.relative('uploads', filepath).replace(/\\/g, '/');
  const moduleName = relativePath.split('/')[0] || '';

  const sql = `
    INSERT INTO uploaded_files (filename, relative_path, mime_type, size, module_name)
    VALUES (?, ?, ?, ?, ?)
  `;
  const [result] = await db.query(sql, [originalname, relativePath, mimetype, size, moduleName]);

  ctx.body = {
    code: 200,
    message: '上传成功',
    data: {
      id: result.insertId,
      originalname,
      url: `${ctx.protocol}://${ctx.host}/${relativePath}`
    }
  };
}

// 批量上传文件夹
// async function uploadFolderHandler(ctx) {
//   const files = ctx.req.files;
//   const values = [];

//   for (const file of files) {
//     const { originalname, mimetype, size, path: filepath } = file;
//     const relativePath = path.basename(filepath)
//     const moduleName = relativePath.split('/')[0] || '';
//     values.push([originalname, relativePath, mimetype, size, moduleName]);
//   }

//   const sql = `INSERT INTO uploaded_files (filename, relative_path, mime_type, size, module_name) VALUES ?`;

//   if (values.length) {
//     await db.query(sql, [values]);
//   }

//   ctx.body = {
//     code: 200,
//     message: '批量上传成功',
//     count: values.length
//   };
// }
async function uploadFolderHandler(ctx) {
  const files = ctx.req.files;
  const paths = ctx.req.body.paths; // 关键：新增
  const pathArray = Array.isArray(paths) ? paths : [paths]; // 保证是数组
  const values = [];

  for (let i = 0; i < files.length; i++) {
    const file = files[i];
    const originalPath = pathArray[i] || file.originalname; // 用前端传来的路径
    const moduleName = originalPath.split('/')[0] || '';
    values.push([
      path.basename(originalPath),          // filename
      originalPath,                         // relative_path
      file.mimetype,
      file.size,
      moduleName
    ]);
  }

  const sql = `INSERT INTO uploaded_files (filename, relative_path, mime_type, size, module_name) VALUES ?`;

  if (values.length) {
    await db.query(sql, [values]);
  }

  ctx.body = {
    code: 200,
    message: '批量上传成功',
    count: values.length
  };
}

// 查询文件
async function getFileList(ctx) {
  const { id, filename, mimetype } = ctx.query;
  const where = [];
  const params = [];

  if (id) {
    where.push('id = ?');
    params.push(id);
  }
  if (filename) {
    where.push('filename LIKE ?');
    params.push(`%${filename}%`);
  }
  if (mimetype) {
    where.push('mime_type LIKE ?');
    params.push(`%${mimetype}%`);
  }

  const whereClause = where.length ? 'WHERE ' + where.join(' AND ') : '';
  const sql = `SELECT * FROM uploaded_files ${whereClause} ORDER BY created_at DESC`;

  const [list] = await db.query(sql, params);

  ctx.body = {
    code: 200,
    data: list.map(item => ({
      ...item,
      url: `${ctx.protocol}://${ctx.host}/${encodeURIComponent(item.relative_path)}`
    }))
  };
}

module.exports = {
  uploadFile,
  getFileList,
  uploadFolderHandler
};
